//
// Created by Jeffrey Wei on 2022/11/2.
//

import Alamofire
import Moya

/// 外部可考虑将其遵守LocalizedError并返回errorDescription值,请求失败后能将能直接拿到localizedDescription的值
public enum NetworkError: Error {
    /// 内部son解析错误,一般不会发生
    case parsingJsonError
    /// 业务错误,会将请求结果传出
    case apiError(response: NetworkResponse)
    /// 无网络错误
    case notReachableNetwork
    /// 服务器导致的错误,如错误的http状态码等,可以通过response获取
    case serviceError(response: Moya.Response?)
}

public extension Error {
    var asNetworkError: NetworkError? {
        if let requestError = self as? NetworkError { return requestError }
        guard let moyaError = self as? MoyaError,
              case let .underlying(error, _) = moyaError
        else { return nil }
        return error.asNetworkError
    }
}
